/*
 * ConnectToServer.java
 *
 * Created on February 25, 2007, 4:17 PM
 */

package d20chat;

import java.io.IOException;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintStream;
import java.awt.*;

/**
 * Window used to setup connection settings for connecting to a server.
 * User must enter username, server address, server port, and server password.
 */
public class ConnectToServer extends javax.swing.JFrame {
    
    private D20Chat tempMain;
    private D20Chatui theGUI;
    
    /** Creates new form ConnectToServer */
    public ConnectToServer() {
        initComponents();
        
        serverPort.setText("4445");
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
/**
     * 
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        lblServerIPAddress = new javax.swing.JLabel();
        serverIPAddress = new javax.swing.JTextField();
        lblServerPassword = new javax.swing.JLabel();
        serverPassword = new javax.swing.JTextField();
        connect = new javax.swing.JButton();
        cancel = new javax.swing.JButton();
        serverPort = new javax.swing.JTextField();
        lblServerPort = new javax.swing.JLabel();
        lblUsername = new javax.swing.JLabel();
        username = new javax.swing.JTextField();

        setTitle("Connect to Server");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        lblServerIPAddress.setForeground(java.awt.Color.darkGray);
        lblServerIPAddress.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblServerIPAddress.setText("Server IP Address:");

        lblServerPassword.setForeground(java.awt.Color.darkGray);
        lblServerPassword.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblServerPassword.setText("Server Password:");

        connect.setText("Connect");
        connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(evt);
            }
        });

        cancel.setText("Cancel");
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        lblServerPort.setText("Port:");

        lblUsername.setForeground(java.awt.Color.darkGray);
        lblUsername.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblUsername.setText("Username:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblServerPassword)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(serverPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(lblUsername)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(username))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(lblServerIPAddress)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(serverIPAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(lblServerPort)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(serverPort, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(connect)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 120, Short.MAX_VALUE)
                        .addComponent(cancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblUsername)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblServerIPAddress)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(serverIPAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblServerPort)
                        .addComponent(serverPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblServerPassword)
                    .addComponent(serverPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(connect)
                    .addComponent(cancel))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    
/********************************************************************************
  Method:
  Description:
  Parameters:
  Used by:
  Uses:
********************************************************************************/    
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // Make sure profile directory and file exists (create if not)
        try 
        {
            boolean serverConn = (new File("serverConn.txt")).exists();
            if (!serverConn) 
            { 
                // serverConn.txt does NOT exist, create it
                boolean success = (new File("serverConn.txt")).createNewFile();
            } 
            else 
            {
                // serverConn.txt does exist
                BufferedReader bin;
                String temp = null;
                
                // Open an input stream
                bin = new BufferedReader(new FileReader("serverConn.txt"));
                temp = bin.readLine();
                this.serverIPAddress.setText(temp);
                temp = bin.readLine();
                this.serverPort.setText(temp);
                        
                        
                // Close our input stream
                bin.close();
            }
        } 
        catch (Exception e) 
        {
            //System.out.println("Could not create profile directory or file!");
        }
        
    }//GEN-LAST:event_formWindowOpened

    
/**
     * 
     */
    private void saveServerConn()
    {        
        try
        {
            FileOutputStream out; // declare a file output object
            PrintStream p; // declare a print stream object

            // Create a new file output stream
            //  connected to "serverConn.txt" path
            out = new FileOutputStream("serverConn.txt");

            // Connect print stream to the output stream
            p = new PrintStream(out);

            // Write profile information to file
            p.println (tempMain.serverIP);
            p.println (tempMain.serverPort);

            p.close();
        }
        // Catches any error conditions
        catch (IOException e)
        {
            System.err.println ("Unable to read from file");
        }
    }
    
    
/********************************************************************************
  Method:
  Description:
  Parameters:
  Used by:
  Uses:
********************************************************************************/
    private void connectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectActionPerformed
        // Set serverIP, serverPort and serverPassword and then connect
        if( username.getText().isEmpty() )
        {
            //no name
            
        }
        else
        {
            try
            {
                tempMain.theUser.setUsername( username.getText().toString() );
            }
            catch( IllegalArgumentException iae )
            {
                String info = "client chat systemMessage client " + iae.getMessage();
                tempMain.InParse.CheckType( info );
            }
        }
        tempMain.serverIP = serverIPAddress.getText().toString();
        tempMain.serverPassword = serverPassword.getText().toString();
        tempMain.serverPort = Integer.parseInt(serverPort.getText().toString());
        tempMain.OpenConnection();

        // saves current server settings to serverConn.txt
        saveServerConn();
        this.setVisible(false);
    }//GEN-LAST:event_connectActionPerformed

    
/********************************************************************************
  Method:
  Description:
  Parameters:
  Used by:
  Uses:
********************************************************************************/ 
    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
        // Hide the form
        this.setVisible(false);
    }//GEN-LAST:event_cancelActionPerformed
    

    
    
/**
     * Class constructor for ConnectToServer, brings up connection window.
     * Displays a window on the screen requesting input from the user and begins
     * connecting to the given server.
     * @param gui Current d20chatui instance.
     * @param main Current D20Chat instance.
     */
    public ConnectToServer(D20Chatui gui, D20Chat main)
    {
        theGUI = gui;
        tempMain = main;
        initComponents();
        if( !tempMain.theUser.getUsername().equals("noname") )
        {
            username.setText(tempMain.theUser.getUsername());
        }
        serverPort.setText("4445");
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancel;
    private javax.swing.JButton connect;
    private javax.swing.JLabel lblServerIPAddress;
    private javax.swing.JLabel lblServerPassword;
    private javax.swing.JLabel lblServerPort;
    private javax.swing.JLabel lblUsername;
    private javax.swing.JTextField serverIPAddress;
    private javax.swing.JTextField serverPassword;
    private javax.swing.JTextField serverPort;
    private javax.swing.JTextField username;
    // End of variables declaration//GEN-END:variables
    
}
